Basics of Object Oriented Programming in C++

Posted on December 15, 2023 by Vishesh Namdev
Python C C++ Java
C++ Programming

Object-Oriented Programming (OOP) is a programming paradigm that uses the concept of "objects" to design and organize code. In OOP, software is structured around real-world entities, and these entities are modeled as objects that encapsulate data and the operations that can be performed on that data.
The main principles of Object-Oriented Programming include:

1. Objects:Objects are instances of classes, which serve as blueprints or templates for creating objects. An object contains data (attributes or properties) and the methods (functions or procedures) that operate on that data.

2. Classes:A class is a user-defined data type that defines a blueprint for creating objects. It specifies the properties (attributes) and behaviors (methods) that the objects of the class will have. Objects are instances of classes.

3. Encapsulation: Encapsulation is the bundling of data and methods that operate on the data within a single unit, i.e., a class. It restricts access to some of the object's components and prevents the accidental modification of data.

4. Inheritance: Inheritance allows a class (subclass or derived class) to inherit the properties and behaviors of another class (superclass or base class). This promotes code reuse and establishes a hierarchy of classes.

5. Polymorphism: Polymorphism allows objects to be treated as instances of their base class, even when they are instances of derived classes. It involves the ability to use a single interface for different types of objects, achieved through function overloading and virtual functions.

6. Abstraction: Abstraction involves simplifying complex systems by modeling classes based on essential properties and behaviors. It focuses on what an object does rather than how it achieves its functionality. Abstract classes may have pure virtual functions, providing an interface without implementation.

Classes and Objects

1. Classes:

A class in C++ is a user-defined data type that represents a blueprint or a template for creating objects. It encapsulates data (attributes or properties) and methods (functions or procedures) that operate on that data. The class keyword is used to define a class in C++.
// Example classCopy Code
class Car {
public:
// Data members
string brand;
int year;

// Member functions
void startEngine() {
cout << "Engine started!" << endl;
}
}

2. Objects:

An object is an instance of a class. It is a concrete realization of the blueprint defined by the class. Objects have attributes (data) and can perform actions (methods) as defined by the class. You can create multiple objects from a single class.
// Creating objects of the classCopy Code
Car myCar; // Object 1
myCar.brand = "Toyota";
myCar.year = 2020;
myCar.startEngine();

Car anotherCar; // Object 2
anotherCar.brand = "Honda";
anotherCar.year = 2019;
anotherCar.startEngine();